'use strict'

let models = require('../models');
let errors = require('../../config/errors');

let Track = models.Track;
let TrackDao = models.TrackDao;
let TrackType = models.TrackType;

function getTracksByAttendances(attendances) {
    return attendances.map(attendance => {
        return getTracksOfStudentInDate(attendance.student, attendance.date);
    });
}

function getTracksOfStudentInDate(student, date) {
    let beginTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0);
    let endTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 24, -1);

    return getTracksOfStudent(student, beginTime, endTime);
}

function getTracksOfStudent(student, beginTime, endTime) {
    return TrackDao.find({
        student: student.id,
        time: {
            $gte: beginTime,
            $lte: endTime
        }
    }).sort((track1, track2) => {
        return track1.time.getTime() > track2.time.getTime()
    });
}

function formatTrack(track) {
    switch ( track.type ) {
    case TrackType.EnterSchool:
        return '进入学校';
    case TrackType.ExitSchool:
        return '离开学校';
    case TrackType.EnterClassroom: 
        return '进入教室：' + track.classroom.name;
    case TrackType.ExitClassroom: 
        return '离开教室：' + track.classroom.name;
    }

    return '未知状态';
}

module.exports = {
    getTracksByAttendances,
    getTracksOfStudentInDate,
    getTracksOfStudent,
    formatTrack
};
